package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.CouponMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.UserCouponMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Coupon;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.UserCoupon;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.CouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private UserCouponMapper userCouponMapper;

    @Override
    public List<UserCoupon> getUserCoupons(Long userId) {
        return userCouponMapper.selectUserCouponsWithDetail(userId);
    }

    @Override
    @Transactional
    public boolean receiveCoupon(Long userId, Long couponId) {
        Coupon coupon = couponMapper.selectById(couponId);
        if (coupon == null || coupon.getRemainCount() <= 0) {
            throw new RuntimeException("优惠券不存在或已领完");
        }

        Integer count = userCouponMapper.countUserCoupon(userId, couponId);
        if (count >= coupon.getLimitPerUser()) {
            throw new RuntimeException("已达领取上限");
        }

        couponMapper.decreaseRemainCount(couponId);

        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(couponId);
        userCoupon.setStatus(0);
        userCoupon.setReceiveTime(LocalDateTime.now());
        userCouponMapper.insert(userCoupon);

        return true;
    }

    @Override
    public List<Coupon> getAvailableCoupons() {
        return couponMapper.selectAvailableCoupons();
    }

    @Override
    public boolean checkCouponAvailability(Long couponId, Long userId) {
        Coupon coupon = couponMapper.selectById(couponId);
        if (coupon == null) return false;
        
        Integer count = userCouponMapper.countUserCoupon(userId, couponId);
        return count < coupon.getLimitPerUser() && coupon.getRemainCount() > 0;
    }
}
